import axios,{InternalAxiosRequestConfig, AxiosResponse} from 'axios';
import { ElMessage,ElMessageBox } from 'element-plus';
// import {useUserStoreHook } from "@/store/modules/user"
const service =axios.create({
  // baseURL:import.meta.env.VITE_APP_BASE_API,
  // baseURL:'/api',
  baseURL:'',
  timeout:50000,
  // headers:{ 'Content-Type': 'application/json;charset=utf-8' }
})

// 请求拦截器
service.interceptors.request.use(
  (config:InternalAxiosRequestConfig)=>{
    // const userStore=useUserStoreHook();
    // if(userStore.token){
    //   config.headers.Authorization=userStore.token;
    // }
    return config
  },
  (error:any)=>{
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  (response:AxiosResponse)=>{
    const {cd,msg}=response.data;
    // 登录成功
    if(cd==='2000'){
      return response.data;
    }else{
      ElMessage.error(msg||'系统出错');
      return Promise.reject(new Error(msg||'Error'));
    }
  },
  (error:any)=>{
    if(error.response.data){
      const {cd,msg}=error.response.data;
      // token 过期，跳转登录页
      if(cd===''){
        ElMessageBox.confirm('当前页面已失效，请重新登录','提示',{
          confirmButtonText:'确定',
          type:'warning'
        }).then(()=>{
          localStorage.clear();
          window.location.href='/'
        })
      }else{
        ElMessage.error(msg||'系统出错');
      }
    }
    return Promise.reject(error.message);
  }
)
export default service